package servlets.event;

import hibernate.method.EventMethods;
import hibernate.model.EventParticipating;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class addEventParticipation
 */
@WebServlet("/addEventParticipation")
public class addEventParticipation extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public addEventParticipation() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String user = request.getParameter("user_id");
		String event = request.getParameter("event_id");
		String maybe = request.getParameter("type");
		
		int user_id = Integer.parseInt(user);
		int event_id = Integer.parseInt(event);
		Boolean maybeB= Boolean.valueOf(maybe);
		
		PrintWriter out = response.getWriter();
		
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		EventMethods ev = new EventMethods();
		if(ev.findByUserEvent(sessionFactory, session, user_id, event_id).size()>0){
		EventParticipating ep = ev.findByUserEvent(sessionFactory, session, user_id, event_id).get(0);
		ep.setMaybe(maybeB);
		}
		else 
		ev.addEventPatricipating(sessionFactory, session, event_id, user_id, maybeB);
		
		
		try {
			session.getTransaction().commit();
			out.println("<script type=\"text/javascript\">alert(\"Uczestnictwo dodane\"); window.location.href = \"social/index.jsp?page=events&group=takePart\";</script>");
		} catch (Exception e) {
			out.println("<script type=\"text/javascript\">alert(\"Uczestnictwo nie dodane\"); window.location.href = \"social/index.jsp?page=events&group=takePart\";</script>");
		}
		
		
		
	}

}
